'use client';

import React, { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import AppHeader from '@/components/ui/app-header';
import Link from 'next/link';
import {
  CheckCircleIcon,
  ClockIcon,
  ArrowPathIcon,
  ExclamationCircleIcon,
  PlusIcon,
  FunnelIcon,
  ArrowsUpDownIcon,
  CheckIcon,
  Square2StackIcon,
} from '@heroicons/react/24/outline';

// 任务状态标签组件
const StatusBadge = ({ status }: { status: string }) => {
  if (!status) return null;
  
  switch (status.toUpperCase()) {
    case 'DONE':
    case 'COMPLETED':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
          <CheckCircleIcon className="mr-1 h-4 w-4" />
          已完成
        </span>
      );
    case 'IN_PROGRESS':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
          <ArrowPathIcon className="mr-1 h-4 w-4" />
          进行中
        </span>
      );
    case 'TODO':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
          <ClockIcon className="mr-1 h-4 w-4" />
          待处理
        </span>
      );
    case 'REVIEW':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-purple-100 text-purple-800">
          <ClockIcon className="mr-1 h-4 w-4" />
          审核中
        </span>
      );
    default:
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
          {status}
        </span>
      );
  }
};

// 优先级标签组件
const PriorityBadge = ({ priority }: { priority: string }) => {
  if (!priority) return null;

  switch (priority.toUpperCase()) {
    case 'HIGH':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
          <ExclamationCircleIcon className="mr-1 h-4 w-4" />
          高
        </span>
      );
    case 'MEDIUM':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
          中
        </span>
      );
    case 'LOW':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
          低
        </span>
      );
    case 'URGENT':
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-600 text-white">
          <ExclamationCircleIcon className="mr-1 h-4 w-4" />
          紧急
        </span>
      );
    default:
      return (
        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
          {priority}
        </span>
      );
  }
};

// 任务类型定义
interface Task {
  id: string;
  title: string;
  description: string | null;
  status: string;
  priority: string;
  assignee: {
    id: string;
    name: string;
    image?: string;
    email?: string;
  } | null;
  dueDate: string | null;
  projectId: string;
  tags?: string[];
  createdAt: string;
  updatedAt: string;
}

export default function TaskPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const projectId = searchParams.get('projectId');
  
  const [tasks, setTasks] = useState<Task[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [filter, setFilter] = useState({
    status: 'all',
    priority: 'all',
  });
  const [sort, setSort] = useState({
    field: 'updatedAt',
    direction: 'desc',
  });

  // 获取任务数据
  useEffect(() => {
    const fetchTasks = async () => {
      setLoading(true);
      setError(null);
      try {
        let url = '/api/task';
        if (projectId) {
          url += `?projectId=${projectId}`;
        }
        
        const response = await fetch(url);
        if (!response.ok) {
          throw new Error(`请求失败: ${response.status}`);
        }
        
        const data = await response.json();
              if (data.success) {
        // 过滤掉没有关联项目的任务
        const filteredTasks = data.data.filter((task: any) => task.projectId);
        setTasks(filteredTasks);
      } else {
        throw new Error(data.message || '获取任务失败');
      }
      } catch (err: any) {
        console.error('获取任务列表失败:', err);
        setError(err.message || '获取任务列表失败');
      } finally {
        setLoading(false);
      }
    };
    
    fetchTasks();
  }, [projectId]);

  // 过滤任务
  const filteredTasks = tasks.filter(task => {
    if (filter.status !== 'all' && task.status?.toUpperCase() !== filter.status.toUpperCase()) return false;
    if (filter.priority !== 'all' && task.priority?.toUpperCase() !== filter.priority.toUpperCase()) return false;
    return true;
  });

  // 排序任务
  const sortedTasks = [...filteredTasks].sort((a, b) => {
    const aValue = a[sort.field as keyof Task];
    const bValue = b[sort.field as keyof Task];
    
    if (typeof aValue === 'string' && typeof bValue === 'string') {
      return sort.direction === 'asc' 
        ? aValue.localeCompare(bValue) 
        : bValue.localeCompare(aValue);
    }
    
    return 0;
  });

  // 处理状态过滤变化
  const handleStatusFilterChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setFilter(prev => ({ ...prev, status: e.target.value }));
  };

  // 处理优先级过滤变化
  const handlePriorityFilterChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setFilter(prev => ({ ...prev, priority: e.target.value }));
  };

  // 处理排序变化
  const handleSortChange = (field: string) => {
    setSort(prev => ({
      field,
      direction: prev.field === field && prev.direction === 'asc' ? 'desc' : 'asc',
    }));
  };

  return (
    <div className="min-h-screen">
      <main className="py-6 px-4 sm:px-6 lg:px-8 max-w-7xl mx-auto">
        <AppHeader
          title={projectId ? "项目任务" : "所有任务"}
          subtitle={projectId ? "查看和管理项目中的任务" : "查看和管理所有任务"}
          actions={
            <button
              type="button"
              onClick={() => router.push(`/task/new${projectId ? `?projectId=${projectId}` : ''}`)}
              className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-[var(--primary-color)] hover:bg-[var(--primary-hover)] focus:outline-none"
            >
              <PlusIcon className="h-5 w-5 mr-2" />
              新建任务
            </button>
          }
        />

        {/* 过滤和排序工具栏 */}
        <div className="mt-6 bg-white p-4 shadow rounded-lg">
          <div className="flex flex-col md:flex-row md:items-center md:justify-between space-y-4 md:space-y-0">
            <div className="flex flex-col sm:flex-row sm:items-center space-y-2 sm:space-y-0 sm:space-x-4">
              <div className="flex items-center">
                <FunnelIcon className="h-5 w-5 text-gray-400 mr-2" />
                <label htmlFor="status-filter" className="text-sm font-medium text-gray-700 mr-2">
                  状态:
                </label>
                <select
                  id="status-filter"
                  value={filter.status}
                  onChange={handleStatusFilterChange}
                  className="block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md"
                >
                  <option value="all">全部</option>
                  <option value="TODO">待处理</option>
                  <option value="IN_PROGRESS">进行中</option>
                  <option value="REVIEW">审核中</option>
                  <option value="DONE">已完成</option>
                </select>
              </div>
              <div className="flex items-center">
                <label htmlFor="priority-filter" className="text-sm font-medium text-gray-700 mr-2">
                  优先级:
                </label>
                <select
                  id="priority-filter"
                  value={filter.priority}
                  onChange={handlePriorityFilterChange}
                  className="block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm rounded-md"
                >
                  <option value="all">全部</option>
                  <option value="LOW">低</option>
                  <option value="MEDIUM">中</option>
                  <option value="HIGH">高</option>
                  <option value="URGENT">紧急</option>
                </select>
              </div>
            </div>
            <div className="flex items-center space-x-4">
              <span className="text-sm font-medium text-gray-700">排序:</span>
              <button
                type="button"
                onClick={() => handleSortChange('title')}
                className={`px-3 py-2 text-sm font-medium rounded-md ${
                  sort.field === 'title' 
                    ? 'bg-gray-100 text-gray-900' 
                    : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                }`}
              >
                标题
                {sort.field === 'title' && (
                  <ArrowsUpDownIcon className="inline-block h-4 w-4 ml-1" />
                )}
              </button>
              <button
                type="button"
                onClick={() => handleSortChange('priority')}
                className={`px-3 py-2 text-sm font-medium rounded-md ${
                  sort.field === 'priority' 
                    ? 'bg-gray-100 text-gray-900' 
                    : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                }`}
              >
                优先级
                {sort.field === 'priority' && (
                  <ArrowsUpDownIcon className="inline-block h-4 w-4 ml-1" />
                )}
              </button>
              <button
                type="button"
                onClick={() => handleSortChange('updatedAt')}
                className={`px-3 py-2 text-sm font-medium rounded-md ${
                  sort.field === 'updatedAt' 
                    ? 'bg-gray-100 text-gray-900' 
                    : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                }`}
              >
                更新时间
                {sort.field === 'updatedAt' && (
                  <ArrowsUpDownIcon className="inline-block h-4 w-4 ml-1" />
                )}
              </button>
            </div>
          </div>
        </div>

        {/* 任务列表 */}
        <div className="mt-6">
          {loading ? (
            <div className="flex justify-center py-12">
              <div className="animate-pulse text-gray-500">加载任务中...</div>
            </div>
          ) : error ? (
            <div className="bg-red-50 p-4 rounded-md">
              <div className="flex">
                <div className="flex-shrink-0">
                  <ExclamationCircleIcon className="h-5 w-5 text-red-400" aria-hidden="true" />
                </div>
                <div className="ml-3">
                  <h3 className="text-sm font-medium text-red-800">加载任务时出错</h3>
                  <div className="mt-2 text-sm text-red-700">
                    <p>{error}</p>
                  </div>
                </div>
              </div>
            </div>
          ) : sortedTasks.length === 0 ? (
            <div className="bg-white shadow rounded-lg p-6 text-center">
              <p className="text-gray-500">没有找到符合条件的任务</p>
            </div>
          ) : (
            <div className="bg-white shadow overflow-hidden sm:rounded-md">
              <ul className="divide-y divide-gray-200">
                {sortedTasks.map((task) => (
                  <li key={task.id}>
                    <div className="flex items-center px-4 py-4 sm:px-6">
                      <div className="mr-4 flex-shrink-0">
                        <button
                          type="button"
                          onClick={async (e) => {
                            e.preventDefault();
                            e.stopPropagation();
                            try {
                              // 切换任务状态
                              const newStatus = task.status.toUpperCase() === 'DONE' ? 'TODO' : 'DONE';
                              const response = await fetch(`/api/task?id=${task.id}`, {
                                method: 'PUT',
                                headers: {
                                  'Content-Type': 'application/json',
                                },
                                body: JSON.stringify({ status: newStatus }),
                              });
                              
                              if (response.ok) {
                                // 更新本地状态
                                const { data } = await response.json();
                                setTasks(tasks => tasks.map(t => 
                                  t.id === task.id ? { ...t, status: data.status } : t
                                ));
                              }
                            } catch (error) {
                              console.error('更新任务状态失败:', error);
                            }
                          }}
                          className="h-5 w-5 text-gray-400 hover:text-gray-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                          aria-label={task.status.toUpperCase() === 'DONE' ? '标记为待处理' : '标记为已完成'}
                        >
                          {task.status.toUpperCase() === 'DONE' ? (
  <CheckCircleIcon className="h-5 w-5 text-green-500" />
) : (
  <div className="h-5 w-5 rounded border border-gray-400"></div>
)}
                        </button>
                      </div>
                      <Link 
                        href={`/task/${task.id}`}
                        className="block hover:bg-gray-50 flex-1"
                      >
                        <div className="px-0 py-0">
                          <div className="flex items-center justify-between">
                            <div className="flex items-center">
                              <p className="text-sm font-medium text-[var(--primary-color)] truncate">
                                {task.title}
                              </p>
                            </div>
                            <div className="flex space-x-2">
                              <StatusBadge status={task.status} />
                              <PriorityBadge priority={task.priority} />
                            </div>
                          </div>
                          <div className="mt-2 sm:flex sm:justify-between">
                            <div className="sm:flex">
                              <p className="flex items-center text-sm text-gray-500 truncate">
                                {task.description && task.description.length > 100
                                  ? `${task.description.substring(0, 100)}...`
                                  : task.description || '无描述'}
                              </p>
                            </div>
                            <div className="mt-2 flex items-center text-sm text-gray-500 sm:mt-0">
                              <p>
                                更新于 {new Date(task.updatedAt).toLocaleDateString('zh-CN')}
                              </p>
                            </div>
                          </div>
                          {task.tags && task.tags.length > 0 && (
                            <div className="mt-2 flex flex-wrap gap-1">
                              {task.tags.map((tag) => (
                                <span
                                  key={tag}
                                  className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-800"
                                >
                                  {tag}
                                </span>
                              ))}
                            </div>
                          )}
                        </div>
                      </Link>
                    </div>
                  </li>
                ))}
              </ul>
            </div>
          )}
        </div>
      </main>
    </div>
  );
} 